package com.atguigu.spzx.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.user.mapper.UserInfoMapper;
import com.atguigu.spzx.user.service.UserInfoService;
import com.dyw.spzx.common.excepiton.GuiguException;
import com.dyw.spzx.model.dto.user.UserLoginDto;
import com.dyw.spzx.model.dto.user.UserRegisterDto;
import com.dyw.spzx.model.entity.user.UserInfo;
import com.dyw.spzx.model.vo.common.ResultCodeEnum;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserInfoServiceImpl implements UserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    // 用户注册
    @Transactional
    @Override
    public void register(UserRegisterDto userRegisterDto) {
        // 获取用户注册信息
        String username = userRegisterDto.getUsername();
        String password = userRegisterDto.getPassword();
        String nickName = userRegisterDto.getNickName();
        String code = userRegisterDto.getCode();

        // 校验数据是否为空
        if (StringUtils.isEmpty(username) ||
                StringUtils.isEmpty(password) ||
                StringUtils.isEmpty(nickName)) {
            throw new GuiguException(ResultCodeEnum.USER_CANNOT_EMPTY_ERROR);
        }
        if (StringUtils.isEmpty(code)) {
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR_CAPTCHA);
        }

        // 校验验证码是否正确
        String codeValueRedis = redisTemplate.opsForValue().get(username);

        if (StringUtils.isEmpty(codeValueRedis)) {
            throw new GuiguException(ResultCodeEnum.LOGIN_CAPTCHA_OVERDUE);
        }
        if (!code.equals(codeValueRedis)) {
            throw new GuiguException(ResultCodeEnum.LOGIN_CAPTCHA_MISTAKEN);
        }

        UserInfo userInfo = userInfoMapper.getUserInfoByUserName(username);
        if (userInfo != null && userInfo.getStatus() == 0) {
            throw new GuiguException(ResultCodeEnum.USER_ERROR);
        }
        if (userInfo != null) {
            throw new GuiguException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }

        // 保存用户信息
        userInfo = new UserInfo();
        userInfo.setUsername(username);
        userInfo.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        userInfo.setNickName(nickName);
        userInfo.setPhone(username);
        userInfo.setStatus(1);
        userInfo.setSex(0);

        userInfo.setAvatar("http://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83eoj0hHXhgJNOTSOFsS4uZs8x1ConecaVOB8eIl115xmJZcT4oCicvia7wMEufibKtTLqiaJeanU2Lpg3w/132");
        userInfoMapper.saveUserInfo(userInfo);

        // 删除Redis中的数据
        redisTemplate.delete(username);

    }

    // 用户登录
    @Override
    public String login(UserLoginDto userLoginDto) {
        String username = userLoginDto.getUsername();
        String password = userLoginDto.getPassword();

        // 校验参数
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            throw new GuiguException(ResultCodeEnum.USER_CANNOT_EMPTY_ERROR);
        }
        UserInfo userInfo = userInfoMapper.getUserInfoByUserName(username);
        if (userInfo == null) {
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR_USER);
        }
        // 验证密码是否正确
        String md5InputPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!md5InputPassword.equals(userInfo.getPassword())){
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR_SEALING);
        }

        // 校验该账号是否被禁
        if (userInfo.getStatus() == 0) {
            throw new GuiguException(ResultCodeEnum.USER_ERROR);
        }

        // 生成token
        String token = UUID.randomUUID().toString().replaceAll("-","");
        redisTemplate.opsForValue().set("user:spzx:" + token, JSON.toJSONString(userInfo),30, TimeUnit.DAYS);

        return token;
    }
}
